import { useState, useCallback, useRef } from 'react';
import { useRequest } from 'ahooks';
import nl2sqlService from '@/api/services/nl2sqlService';

interface TaskProgressOptions {
  onSuccess?: (data: any) => void;
  onError?: (error: any) => void;
  onProgress?: (progress: number) => void;
  pollingInterval?: number;
  maxRetries?: number;
}

interface TaskProgressState {
  progress: number;
  isCompleted: boolean;
  errorMessage: string;
  isPolling: boolean;
}

export const useTaskProgress = (options: TaskProgressOptions = {}) => {
  const {
    onSuccess,
    onError,
    onProgress,
    pollingInterval = 2000,
    maxRetries = 3,
  } = options;

  const [state, setState] = useState<TaskProgressState>({
    progress: 0,
    isCompleted: false,
    errorMessage: '',
    isPolling: false,
  });

  const retryCountRef = useRef(0);
  const shouldPollRef = useRef(false);
  const taskIdRef = useRef<string>('');

  // 使用 useRequest 进行优化的轮询
  const { run: pollProgress } = useRequest(
    async (taskId: string) => {
      if (!shouldPollRef.current || state.isCompleted) {
        return;
      }

      try {
        const progressData = await nl2sqlService.getTaskProgress(taskId);
        console.log('progressData', progressData);

        // 重置重试计数
        retryCountRef.current = 0;

        // 更新进度
        if (progressData.progress !== undefined) {
          setState(prev => ({ ...prev, progress: progressData.progress }));
          onProgress?.(progressData.progress);
        }

        if (progressData.progress === 100) {
          // 任务成功
          setState(prev => ({
            ...prev,
            progress: 100,
            isCompleted: true,
            isPolling: false,
          }));
          shouldPollRef.current = false;
          onSuccess?.(progressData);
        } else if (progressData.ret_code !== 0) {
          // 任务失败
          setState(prev => ({
            ...prev,
            errorMessage: progressData.ret_message || '任务执行失败',
            isCompleted: true,
            isPolling: false,
          }));
          shouldPollRef.current = false;
          onError?.(progressData);
        } else {
          // 任务仍在进行中，继续轮询
          if (shouldPollRef.current) {
            setTimeout(() => {
              pollProgress(taskId);
            }, pollingInterval);
          }
        }
      } catch (error) {
        console.error('获取任务进度失败:', error);
        retryCountRef.current += 1;

        // 如果重试次数过多，停止轮询
        if (retryCountRef.current >= maxRetries) {
          setState(prev => ({
            ...prev,
            errorMessage: '网络连接超时，请检查网络后重试',
            isCompleted: true,
            isPolling: false,
          }));
          shouldPollRef.current = false;
          onError?.(error);
          return;
        }

        // 如果轮询仍在进行，继续尝试
        if (shouldPollRef.current && !state.isCompleted) {
          setTimeout(() => {
            pollProgress(taskId);
          }, pollingInterval);
        }
      }
    },
    {
      manual: true,
    }
  );

  // 开始轮询
  const startPolling = useCallback((taskId: string) => {
    taskIdRef.current = taskId;
    shouldPollRef.current = true;
    retryCountRef.current = 0;
    setState(prev => ({
      ...prev,
      progress: 0,
      isCompleted: false,
      errorMessage: '',
      isPolling: true,
    }));
    pollProgress(taskId);
  }, [pollProgress]);

  // 停止轮询
  const stopPolling = useCallback(() => {
    shouldPollRef.current = false;
    setState(prev => ({
      ...prev,
      isPolling: false,
    }));
  }, []);

  // 重置状态
  const reset = useCallback(() => {
    shouldPollRef.current = false;
    retryCountRef.current = 0;
    setState({
      progress: 0,
      isCompleted: false,
      errorMessage: '',
      isPolling: false,
    });
  }, []);

  return {
    ...state,
    startPolling,
    stopPolling,
    reset,
  };
};
